package com.qyhl.module_practice.substreet;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.module_practice.common.Town2ListPagerAdapter;
import com.qyhl.module_practice.substreet.fragment.SubStreetFragment;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeHomeMenuBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeListBean;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.vertical.QTabView;
import com.qyhl.webtv.commonlib.utils.vertical.TabAdapter;
import com.qyhl.webtv.commonlib.utils.vertical.TabView;
import com.qyhl.webtv.commonlib.utils.vertical.VerticalTabLayout;
import com.qyhl.webtv.commonlib.utils.vertical.VerticalViewPager;
import com.weavey.loading.lib.LoadingLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

public class SubStreetMainFragment extends BaseFragment implements SubStreetMainContract.SubStreetMainView {
    @BindView(R2.id.tablayout)
    VerticalTabLayout tablayout;
    @BindView(R2.id.verticalviewpager)
    VerticalViewPager verticalViewPager;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private String instId;

    public void setInstId(String instId) {
        this.instId = instId;
    }

    private int volStatus;

    private String volId;

    public void setVolId(String volId) {
        this.volId = volId;
    }

    public void setVolStatus(int volStatus) {
        this.volStatus = volStatus;
    }

    private SubStreetMainPresenter mPresenter;

    private static final float MIN_SCALE = 0.75f;
    private static final float MIN_ALPHA = 0.75f;

    private List<String> nameList;

    private PracticeHomeMenuBean bean;

    public void setBean(PracticeHomeMenuBean bean) {
        this.bean = bean;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.practice_fragment_substreet_main, null);
    }

    @Override
    protected void create() {
        mPresenter = new SubStreetMainPresenter(this);
        loadMask.setStatus(LoadingLayout.Loading);
        mPresenter.getList(instId);
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getList(instId);
            }
        });

        tablayout.addOnTabSelectedListener(new VerticalTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabView tab, int position) {
                verticalViewPager.setCurrentItem(position);
                for (int i = 0; i < nameList.size(); i++) {
                    if (i == position) {
                        tab.setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.global_base));
                    } else {
                        tablayout.getTabAt(i).setBackgroundColor((ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.white)));
                    }
                }

            }

            @Override
            public void onTabReselected(TabView tab, int position) {

            }
        });

        verticalViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tablayout.setTabSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    @Override
    public void initImmersionBar() {

    }


    public static SubStreetMainFragment newInstance(String instId, int volStatus, String volId, PracticeHomeMenuBean bean) {
        SubStreetMainFragment fragment = new SubStreetMainFragment();
        fragment.setInstId(instId);
        fragment.setVolStatus(volStatus);
        fragment.setVolId(volId);
        fragment.setBean(bean);
        return fragment;
    }

    @Override
    public void setList(List<PracticeListBean> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");

        nameList = new ArrayList<>();
        ArrayList<Fragment> fragmentList = new ArrayList<>();
        if (bean.getAdditional() != null && bean.getAdditional().size() > 0) {
            for (int i = 0; i < bean.getAdditional().size(); i++) {
                PracticeHomeMenuBean.Additional additional = bean.getAdditional().get(i);
                nameList.add(additional.getTitle());
                if (additional.getStyleName().equals("企业服务站列表")) {
                    fragmentList.add(SubStreetFragment.newInstance(volId, volStatus, instId, "2"));
                }else if(additional.getStyleName().equals("实践中心")){
                    fragmentList.add(SubStreetFragment.newInstance(volId, volStatus, instId, "3"));
                }else{
                    fragmentList.add(SubStreetFragment.newInstance(volId, volStatus, instId, "1"));
                }
            }
        }


        for (int i = 0; i < beanList.size(); i++) {
            nameList.add(beanList.get(i).getName());
            fragmentList.add(SubStreetFragment.newInstance(volId, volStatus, beanList.get(i).getId() + "", "1"));
        }


        tablayout.setTabAdapter(new MyTabAdapter(nameList));
        try {
            tablayout.getTabAt(0).setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.global_base));
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (int i = 0; i < nameList.size(); i++) {
            tablayout.getTabAt(i).setPadding(0, 100, 0, 100);
        }

        Town2ListPagerAdapter mPagerAdapter = new Town2ListPagerAdapter(getChildFragmentManager(), fragmentList);
        mPagerAdapter.setData(nameList);
        verticalViewPager.setAdapter(mPagerAdapter);
        verticalViewPager.setPageMargin(getResources().
                getDimensionPixelSize(R.dimen.practice_pagemargin));
        verticalViewPager.setPageMarginDrawable(new ColorDrawable(
                ContextCompat.getColor(getContext(), R.color.white)));

        verticalViewPager.setPageTransformer(true, new ViewPager.PageTransformer() {
            @Override
            public void transformPage(View view, float position) {
                int pageWidth = view.getWidth();
                int pageHeight = view.getHeight();

                if (position < -1) { // [-Infinity,-1)
                    // This page is way off-screen to the left.
                    view.setAlpha(0);

                } else if (position <= 1) { // [-1,1]
                    // Modify the default slide transition to shrink the page as well
                    float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
                    float vertMargin = pageHeight * (1 - scaleFactor) / 2;
                    float horzMargin = pageWidth * (1 - scaleFactor) / 2;
                    if (position < 0) {
                        view.setTranslationY(vertMargin - horzMargin / 2);
                    } else {
                        view.setTranslationY(-vertMargin + horzMargin / 2);
                    }

                    // Scale the page down (between MIN_SCALE and 1)
                    view.setScaleX(scaleFactor);
                    view.setScaleY(scaleFactor);

                    // Fade the page relative to its size.
                    view.setAlpha(MIN_ALPHA +
                            (scaleFactor - MIN_SCALE) /
                                    (1 - MIN_SCALE) * (1 - MIN_ALPHA));

                } else { // (1,+Infinity]
                    // This page is way off-screen to the right.
                    view.setAlpha(0);
                }
            }
        });
    }

    @Override
    public void setError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        if (!NetUtil.isNetworkAvalible(getContext())) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }


    @OnClick(R2.id.search_txt)
    public void onViewClicked() {
        Bundle bundle = new Bundle();
        bundle.putString("id", instId);
        RouterManager.router(ARouterPathConstant.PRACTICE_SEARCH, bundle);

    }

    class MyTabAdapter implements TabAdapter {

        List<String> titles;

        MyTabAdapter(List<String> titles) {
            this.titles = titles;
        }

        public void setTitles(List<String> titles) {
            this.titles = titles;
        }

        @Override
        public int getCount() {
            return titles.size();
        }

        @Override
        public int getBadge(int position) {
            return 0;
        }

        @Override
        public QTabView.TabIcon getIcon(int position) {
            return null;
        }

        @Override
        public QTabView.TabTitle getTitle(int position) {
            return new QTabView.TabTitle.Builder(getActivity())
                    .setContent(titles.get(position))
                    .setTextColor(getResources().getColor(R.color.white), getResources().getColor(R.color.global_black_lv1))
                    .build();
        }

        @Override
        public int getBackground(int position) {
            return 0;
        }
    }

}
